﻿namespace JoinBox.Basal;

using System;
using System.Collections.Generic;
using System.IO;
using System.Text;


/// <summary>
/// 遍历桌面资源管理器,获取桌面所有文件夹的路径
/// </summary>
public class ShellWindows : HashSet<Explorer>
{
    /// <summary>
    /// 遍历桌面资源管理器,获取桌面所有文件夹的路径
    /// </summary>
    public ShellWindows()
    {
        var wndList = new List<WindowsAPI.WindowInfo>();
        WindowsAPI.GetAllDesktopWindows(wndList);

        var classArrar = new string[] {
         "WorkerW",
         "ReBarWindow32",
         "Address Band Root",
         "msctls_progress32",
         "Breadcrumb Parent",
         "ToolbarWindow32"
        };

        var displays = new Shell32.GetDisplays();
        foreach (var info in wndList)
        {
            if (info.ClassName != "CabinetWClass")// 资源管理器
                continue;

            var fi = WindowsAPI.RecursionFindWindowClassName(info.Hwnd, classArrar);
            if (fi == IntPtr.Zero)
                continue;

            // 知识:toolbar上的按钮没有handler,要用发送通知信息
            var sb = new StringBuilder(256);
            // 获取窗口名称-路径地址
            WindowsAPI.GetWindowText(fi, sb, sb.Capacity);
            string? path = sb.ToString();
            path = path.Substring(4, path.Length - 4);// 4表示"地址: "...怎么对应每个语言呢?

            // 窗口名称如果是特殊文件夹则不是路径,如"桌面"/"文档"/"音乐"
            if (string.IsNullOrEmpty(Path.GetDirectoryName(path)))
                path = displays.GetPath(path);

            Add(new Explorer
            {
                HWND = info.Hwnd,
                LocationURL = path
            });
        }
    }
}


public struct Explorer
{
    /// <summary>
    /// 句柄
    /// </summary>
    public IntPtr HWND;

    /// <summary>
    /// 文件夹路径
    /// </summary>
    public string? LocationURL;

    /// <summary>
    /// 关闭窗口,关闭文件夹
    /// </summary>
    public void Quit()
    {
        WindowsAPI.SendMessage(HWND, (int)WM.WM_CLOSE, IntPtr.Zero, IntPtr.Zero);
    }
}
